package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.common.util.RequestUtils;
import com.mars.common.util.TokenUtils;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.SysProduct;
import com.mars.module.admin.mapper.SysProductMapper;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysFootHistoryRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysFootHistoryMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysFootHistory;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysFootHistoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户足迹业务层处理
 *
 * @author mars
 * @date 2024-01-25
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysFootHistoryServiceImpl implements ISysFootHistoryService {

    private final SysFootHistoryMapper baseMapper;
    private final SysProductMapper productMapper;
    private final SysUserMapper userMapper;
    private final TokenUtils tokenUtils;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysFootHistory add(SysFootHistoryRequest request) {
        SysFootHistory entity = SysFootHistory.builder().build();
        BeanUtils.copyProperties(request, entity);
        entity.setUserId(ContextUserInfoThreadHolder.get().getId());
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysFootHistoryRequest request) {
        SysFootHistory entity = SysFootHistory.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysFootHistory getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysFootHistory> pageList(SysFootHistoryRequest request) {
        HttpServletRequest servletRequest = RequestUtils.getRequest();
        Long userId = tokenUtils.getUserId(servletRequest);
        request.setUserId(userId);
        Page<SysFootHistory> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysFootHistory> query = this.buildWrapper(request);
        IPage<SysFootHistory> pageRecord = baseMapper.selectPage(page, query);
        List<SysFootHistory> records = pageRecord.getRecords();
        List<SysFootHistory> recordsNew = new ArrayList<>();
        for (SysFootHistory history : records) {
            SysProduct sysProduct = productMapper.selectById(history.getProductId());
            SysUser sysUser = userMapper.selectById(history.getUserId());
            history.setProductName(sysProduct == null ? "" : sysProduct.getName());
            history.setPicture(sysProduct == null ? "" : sysProduct.getPicture());
            history.setUserName(sysUser == null ? "" : sysUser.getUserName());
            recordsNew.add(history);
        }
        if (StringUtils.isNotBlank(request.getProductName())) {
            recordsNew = recordsNew.stream().filter(e -> e.getProductName().contains(request.getProductName())).collect(Collectors.toList());
        }
        recordsNew = recordsNew.stream().sorted((m1, m2) -> m2.getCreateTime().compareTo(m1.getCreateTime())).collect(Collectors.toList());
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysFootHistory> list(SysFootHistoryRequest request) {
        LambdaQueryWrapper<SysFootHistory> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysFootHistory> buildWrapper(SysFootHistoryRequest param) {
        LambdaQueryWrapper<SysFootHistory> query = new LambdaQueryWrapper<>();
        if (param.getUserId() != null) {
            query.eq(SysFootHistory::getUserId, param.getUserId());
        }
        if (param.getProductId() != null) {
            query.eq(SysFootHistory::getProductId, param.getProductId());
        }
        return query;
    }

}
